(function(managerModule){
    managerModule.directive('extUploader', ['$parse', 'uploadService', function($parse, uploadService){
				return {
					restrict: 'AE',
					require: '?ngModel',

					// begin link ***
					link: function(scope, el, attrs, ctrl){
						// console.log(Uploader)
						var opts = scope.$eval(attrs.extUploader) || {};

						if(!opts.uploader){
							console.log('Parameter required : uploader!');
							return;
						}
						
						//opts.uploader = Consts.getAppPath(opts.uploader); 反复初始化会生成多余目录
					
						// default parameters
						var props = {};
						props.on_select = function(file_name){
							if(opts.paramsModel){
								var getter = $parse(opts.paramsModel);
								el.data('formData', getter(scope));
							}
						};
						props.on_before_upload = function(file_name){
							var flag = true;
							var returnParams = null;
							if(opts.fnBeforeUpload){
								var getter = $parse(opts.fnBeforeUpload);
								var fnTarget = getter(scope);
								if(fnTarget){
									scope.$apply(function(){
										flag = fnTarget(file_name,opts);
									});
								}
							}
							
							if(flag){
								el.attr('disabled', true).addClass('disabled');
								var targetTipsEl = opts.uploadTipsSelector ? $(opts.uploadTipsSelector) : el.siblings('span.tips').css('display', 'inline');
								targetTipsEl.text(opts.uploadTips || '文件上传中...').show();
								//使附件上传的校验生效2016年3月30日 殷万洋
								returnParams = opts.uploader;
							}
							return returnParams;
					
						};
						props.on_complete = function(file_name, json){
							el.removeAttr('disabled').removeClass('disabled');
							var targetTipsEl = opts.uploadTipsSelector ? $(opts.uploadTipsSelector) : el.siblings('span.tips');
							targetTipsEl.hide();
					
							if(json.error){
								alert(json.error);
								return;
							}
					
							console.log(file_name);
							console.log(JSON.stringify(json));
					
							if(opts.fn){
								var getter = $parse(opts.fn);
								var fnTarget = getter(scope);
								if(fnTarget){
									scope.$apply(function(){
										fnTarget(file_name, json);
									});
								}
							}
						};
						angular.extend(props, opts);
						var uploader = new uploadService(el, props);
						uploader.init_upload();
					
						// before choose 
						if(opts.fnBeforeChoose){
							el.click(function(e){
								console.log('====================');
								var getter = $parse(opts.fnBeforeChoose);
								var fnTarget = getter(scope);
								var flag = true;
								if(fnTarget){
									scope.$apply(function(){
										flag = fnTarget();
									});
								}
					
								// do not choose
								if(!flag)
									e.preventDefault();
							});
						}
					}
					// end link ***

				};
			}]);

})(managerModule);